<?php

namespace App\Http\Middleware;

use App\Exceptions\ApiException;
use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

/**
 * passport登录处理中间件
 *
 * Class OAuthLogin
 * @package App\Http\Middleware
 */
class OAuthLogin
{
    /**
     * Handle an incoming request.
     *
     * @param $request
     * @param Closure $next
     *
     * @return mixed
     * @throws ApiException
     */
    public function handle(Request $request, Closure $next)
    {
        $email = $request->input('email');
        $password = $request->input('password');
        $loginData = ['email' => $email, 'password' => $password];
        $validator = Validator::make($loginData, [
            'email' => 'required|string|email',
            'password' => 'required|min:8'
        ]);
        if ($validator->fails()) {
            throw new ApiException($validator->getMessageBag()->first(), 10102);
        }

        $request->request->add([
            "username" => $email,
            "password" => $password,
        ]);

        return $next($request);
    }
}
